import json
import re

class Config:
    CONFIG_FILENAME = "openlist.json"
    # # -------------------------------默认配置----------------------------
    # # python 格式 = load(filename)
    # configs = {KEY_SERIAL_PORT: "COM5"}
    configs = {}

    def load(self, filename=CONFIG_FILENAME):
        config = self.configs
        try:
            print("open json file")
            file = open(filename, encoding='utf-8')

            print("load json file")
            config = json.load(file, strict=False)
            file.close()
        except IOError:
            print("open json IOERROR,Use default config")
            return False
        except json.decoder.JSONDecodeError:
            print("open json json.decoder.JSONDecodeError,Use default config")
            return False

        self.configs = config
        return True

    def save(self, filename=CONFIG_FILENAME):
        file = open(filename, "w", encoding='utf-8')
        file.write(json.dumps(self.configs, ensure_ascii=False, indent=2))
        file.close()
        # json.dump(self.configs, file, ensure_ascii=False, indent=4)
        # file.close()

    def printJsonStr(self):
        json_formatted_str = json.dumps(self.configs, indent=2, ensure_ascii=False)
        print(json_formatted_str)

    def printJsonPython(self):
        print(self.configs)

    # 获取数据
    def getTabs(self):
        self.tabs = list(self.configs)
        return self.tabs

    def getTabMenu(self, tabsn):
        self.getTabs()
        return list(self.configs[self.tabs[tabsn]])

    def getTabMenuitems(self, tabsn, menusn):
        menu = self.getTabMenu(tabsn)
        return self.configs[self.tabs[tabsn]][menu[menusn]]

    def getdictkey(self, dict):
        return dict.keys()

    def getdictValues(self, dict):
        return dict.values()

    def getTabMenuitem(self, tabsn, menusn, cols):
        listcols = list(self.getTabMenuitems(tabsn, menusn))

        return listcols[cols]

    # 增
    def inserttab(self, tabname):
        if self.configs.get(tabname) is not None:
            print("当前tab %s 已经存在"%tabname)
            return

        dict = {tabname: {"temp": {
            "C": "c:/",
            "D": "D:/",
            "calc": "C:/Windows/System32/calc.exe",
            "control": "C:/Windows/System32/control.exe",
            "mmc": "C:/Windows/System32/mmc.exe",
            "mspaint": "C:/Windows/System32/mspaint.exe",
            "telnet": "C:/Windows/System32/telnet.exe"
        }}}
        self.configs.update(dict)

    def insettabobj(self, tabobj):
        self.configs.update(tabobj)

    def insertMenu(self, tabname, newMenuname):
        if self.configs[tabname].get(newMenuname) is not None:
            print("当前tab %s 中 %s 已经存在"%(tabname, newMenuname))
            return

        dict ={ newMenuname: {
            "C": "c:/",
            "D": "D:/",
            "calc": "C:/Windows/System32/calc.exe",
            "control": "C:/Windows/System32/control.exe",
            "mmc": "C:/Windows/System32/mmc.exe",
            "mspaint": "C:/Windows/System32/mspaint.exe",
            "telnet": "C:/Windows/System32/telnet.exe"
        }}

        self.configs[tabname].update(dict)
        pass

    def insetMenuobj(self, tabname, tabobj):
        self.configs[tabname].update(tabobj)

    def insertItem(self, tabname, Menuname, ItemName):
        if self.configs[tabname][Menuname].get(ItemName) is not None:
            print("当前tab %s menu %s 中 %s 已经存在"%(tabname, Menuname, ItemName))
            return

        dict ={ItemName: "c:/"}

        self.configs[tabname][Menuname].update(dict)
        pass

    def insetItemobj(self, tabname, Menuname, tabobj):
        self.configs[tabname][Menuname].update(tabobj)

    # 删
    def removeTab(self, currentTabName):
        if self.configs.get(currentTabName) is not None:
            self.configs.pop(currentTabName)
        else:
            print("当前的 Tab %s 不存在" % currentTabName)

    def removeMenu(self, tabname, currentMenuName):
        if self.configs[tabname].get(currentMenuName) is not None:
            self.configs[tabname].pop(currentMenuName)
        else:
            print("当前的 Menu %s 不存在" % currentMenuName)

    def removeItem(self, tabname, menuName, currentName):
        if self.configs[tabname][menuName].get(currentName) is not None:
            self.configs[tabname][menuName].pop(currentName)
        else:
            print("当前的 item %s 不存在" % currentName)

    # 修改已经存在tab的text
    def renameTab(self, currentTabName, newTabName):
        if self.configs.get(currentTabName) is not None:
            self.configs[newTabName] = self.configs.pop(currentTabName)
        else:
            print("当前的 Tab %s 不存在" % currentTabName)

    def renameMenu(self, tabname, currentMenuName, newMenuName):
        if self.configs[tabname].get(currentMenuName) is not None:
            self.configs[tabname][newMenuName] = self.configs[tabname].pop(currentMenuName)
        else:
            print("当前的 Menu %s 不存在" % currentMenuName)

    def renameItemName(self, tabname, menuName, currentName, newnNme):
        if self.configs[tabname][menuName].get(currentName) is not None:
            self.configs[tabname][menuName][newnNme] = self.configs[tabname][menuName].pop(currentName)
        else:
            print("当前的 item %s 不存在" % currentName)

    def resetItemValue(self, tabname, menuName, itemName, value):
        if self.configs[tabname][menuName].get(itemName) is not None:
            print("当前的 item %s value ,修改为 %s " % (itemName, value))
            self.configs[tabname][menuName][itemName] = value
        else:
            print("当前的 item %s 不存在" % itemName)

    # 查

    def searchItem(self, name, value=0):
        pattern = '.*'.join(name)  # Converts 'djm' to 'd.*j.*m'
        regex = re.compile(pattern)  # Compiles a regex.
        retlist = []
        for tabcn, tab in enumerate(self.configs):
            for linkitemcn, menu in enumerate(self.configs[tab]):
                    # print(self.configs[tab][menu])
                    for linkitemnamecn, linkitem in enumerate(self.configs[tab][menu]):
                        # print(linkitem)
                        match = regex.search(linkitem)  # Checks if the current item matches the regex.
                        if match:
                            if value == 0:
                                # suggestions.append(item)
                                print("get success")
                                return tab
                            elif value == 1:
                                retlist.append(linkitem)
                            elif value == 2:
                                retlist.append((tabcn, linkitemcn, linkitemnamecn, linkitem))
        if len(retlist) != 0:
            return retlist
        else:
            return None

if __name__ == "__main__":
    config = Config()
    config.load()
    config.printJsonStr()
    config.printJsonPython()

    # 增加 子item
    config.inserttab("555")
    config.insertMenu("555", "tempMenu")
    config.insertItem("555", "tempMenu", "telnet2")
    config.insetItemobj("555", "tempMenu", {"qq": "asdas"})
    # 删除
    config.removeItem("555", "tempMenu", "telnet2")
    config.removeMenu("555", "tempMenu")
    config.removeTab("555")


    # 修改
    config.renameTab("B05", "B02")
    config.renameMenu("B02", "Git", "Gitlab")
    config.renameItemName("B02", "Gitlab", "SLM系统", "SLM系统1")
    config.resetItemValue("B02", "Gitlab", "SLM系统1", "C:/Users/admin/Desktop/matlab安装完毕后需要的额外操作 - 副本.txt")

    # 查找目标数据
    print(config.getTabs())
    print(config.getTabMenu(0))
    print(config.getTabMenu(1))
    print(config.getTabMenu(2))
    items = config.getTabMenuitems(0, 0)
    print(items)
    print(config.getdictkey(items))
    print(config.getdictValues(items))

    item = config.getTabMenuitem(0, 0, 0)
    print(item)
    config.searchItem("SLM")

    config.save()
